import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getDeviceList, getDeviceStats, getDeviceMonitor } from '@/api/device'
import type { Device } from '@/types'

export const useDeviceStore = defineStore('device', () => {
  // 设备列表
  const deviceList = ref<Device[]>([])
  
  // 设备统计数据
  const deviceStats = ref<any>({})
  
  // 当前选中的设备
  const currentDevice = ref<Device | null>(null)
  
  // 设备监控数据
  const monitorData = ref<any>({})

  // 获取设备列表
  const fetchDeviceList = async (params: any = {}) => {
    try {
      const response = await getDeviceList(params)
      deviceList.value = response.list
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取设备统计
  const fetchDeviceStats = async () => {
    try {
      const response = await getDeviceStats()
      deviceStats.value = response
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取设备监控数据
  const fetchMonitorData = async () => {
    try {
      const response = await getDeviceMonitor()
      monitorData.value = response
      return response
    } catch (error) {
      throw error
    }
  }

  // 设置当前设备
  const setCurrentDevice = (device: Device | null) => {
    currentDevice.value = device
  }

  // 更新设备状态
  const updateDeviceStatus = (deviceId: number, status: string) => {
    const device = deviceList.value.find(d => d.id === deviceId)
    if (device) {
      device.status = status as any
    }
  }

  return {
    deviceList,
    deviceStats,
    currentDevice,
    monitorData,
    fetchDeviceList,
    fetchDeviceStats,
    fetchMonitorData,
    setCurrentDevice,
    updateDeviceStatus
  }
})